#include "cJSON/cJSON.h"
#include "log/log.h"
#include <string.h>
#include <stdlib.h>
#include "app_common.h"

//chars: 1  2  4  XX  abcd
//json: {"conn_type":1,"conn_id":"5858","msg":"61626364"}
/**
 * @brief 将字符数组格式的消息数据转换为Json格式字符串
 * * @param charsstr 字符数组格式的消息数据
 * @param chars_len 字符数组长度
 * @return Json格式字符串(NULL失败)
 */
char *app_message_chars2Json(char *charsstr,int chars_len)
{
    //1.从chars中读取出conn_type,id_len,msg_len,id,msg
    int conn_type = charsstr[0];
    int id_len = charsstr[1];
    int msg_len = charsstr[2];

    //判断字符数组的长度是否正确
    if(chars_len < 3 + id_len + msg_len)
    {
        log_error("chars_len is not correct");
        return NULL;
    }

    char id[id_len];
    memcpy(id,charsstr + 3,id_len);
    char msg[msg_len];
    memcpy(msg,charsstr + 3 + id_len,msg_len);

    // char *id = charsstr + 3;
    // char *msg = charsstr + 3 + id_len;


    //2.生成16进制id和msg字符串
    char *id_hexstr = app_common_chars2Hexstr(id,id_len);
    char *msg_hexstr = app_common_chars2Hexstr(msg,msg_len);

    //3.生成json格式消息
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root,"conn_type",conn_type);
    cJSON_AddStringToObject(root,"id",id_hexstr);
    cJSON_AddStringToObject(root,"msg",msg_hexstr);
    char *json = cJSON_PrintUnformatted(root);

    //4.释放内存
    cJSON_Delete(root);
    free(id_hexstr);
    free(msg_hexstr);

    //5.返回json格式消息
    return json;

}




//json: {"conn_type":1,"conn_id":"5858","msg":"61626364"}
//chars: 1  2  4  XX  abcd
/**
 * @brief 将Json格式字符串转换为字符数组格式的消息数据
 * * @param json Json格式字符串
 * @param chars_buff 字符数组缓冲区
 * @param buff_size 字符数组缓冲区大小(容器大小)
 * @return 字符数组实际长度(-1失败)
 */
int app_message_json2Chars(char *json,char *chars_buff,int buff_size)
{
    //1.解析json格式字符串,得到conn_type,id_hexstr,msg_hexstr
    cJSON *root_obj = cJSON_Parse(json);
    int conn_type = cJSON_GetObjectItem(root_obj,"conn_type")->valueint;
    char *id_hexstr = cJSON_GetObjectItem(root_obj,"id")->valuestring;
    char *msg_hexstr = cJSON_GetObjectItem(root_obj,"msg")->valuestring;

    //2.将16进制的id_hexstr和msg_hexstr转换为charstr类型的字符数组
    int id_len = -1;
    int msg_len = -1;
    char *id = app_common_hexstr2Chars(id_hexstr,&id_len);
    char *msg = app_common_hexstr2Chars(msg_hexstr,&msg_len);

    //判断字符数组缓冲区是否足够
    if(buff_size < 3+id_len+msg_len)
    {
        log_error("buff_size is not enough");
        //释放内存
        cJSON_Delete(root_obj);
        free(id);
        free(msg);
        return -1;
    }

    //3.向chars_buff中拼接字符数组消息
    chars_buff[0] = conn_type;
    chars_buff[1] = id_len;
    chars_buff[2] = msg_len;
    memcpy(chars_buff+3,id,id_len);
    memcpy(chars_buff+3+id_len,msg,msg_len);

    //4.返回拼接的字符数组消息长度
    return 3+id_len+msg_len;

}